<?php

namespace App\Service\Pay\SysType;

use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\OpenShopCacheEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\OrderPaymentSucceededEvent;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use Illuminate\Support\Facades\Cache;

class PayLeagueService extends BasePaySysTypeService
{
    public function valid(): void
    {
        // 订单已作废
        if ($this->signOrderModel->status == SignOrderEnum::ORDER_STATUS_NO) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_STATUS_DEL)
            );
        }

        // 判断阶段
        if ($this->signOrderModel->step < SignOrderEnum::STEP_2) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_BEFORE_PAY)
            );
        }

        // 判断支付状态
        if ($this->signOrderModel->step > SignOrderEnum::STEP_3 && $this->signOrderModel->payStatus == SignOrderEnum::PAY_STATUS_OK) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_ERR_REPEAT_PAY)
            );
        }
    }

    public function paySuccessCheck(): bool
    {
        // 主订单已支付完成、直接返回成功 - 幂等
        if ($this->orderModel->payStatus == SignOrderEnum::PAY_STATUS_OK) {
            return true;
        }

        return false;
    }

    public function priceLists(): array
    {
        // 定金模式需要显示单店
        if ($this->orderModel->contractRel) {
            $lists = $this->orderModel->contractRel->costLists();

            // 定金模式，付定金 = 全部；尾款 = 单店
            // 传统模式，全部
            if ($this->orderModel->contractRel->mode == OpenShopContractTemplateModel::MODE_3) {

                $mainProcess = $this->orderModel->progressRel;

                // 主单定金全部；其他单店
                if ($mainProcess->childOrder != MainProcessEnum::CHILD_ORDER_0 || $this->orderModel->step > SignOrderEnum::STEP_3) {
                    foreach ($lists as &$v) {
                        $v['price'] = (int)($v['price'] / $this->orderModel->contractRel->shopCount);
                    }
                }
            }
        }

        return $lists;
    }

    public function paySuccessSaveOrder(int $amount): void
    {
        $this->orderModel->onePaySuccess($amount);

        // 更新主表的当前nowStepStatus
        if ($this->orderModel->step == SignOrderEnum::STEP_4) {
            OpenShopMainProcessModel::updateNowStepStatus($this->signOrderModel->orderNo, MissionTemplateEnum::STEP_STATUS_2);
        }
    }

    public function paySuccessAfter(): void
    {
        // 如果是定金模式 && 子单。把子单金额置为0，并加到主单上去
        if ($this->orderModel->payStatus == SignOrderEnum::PAY_STATUS_OK && $this->orderModel->payPrice > 0) {

            if ($this->orderModel->contractRel->mode == OpenShopContractTemplateModel::MODE_3 && $this->orderModel->progressRel->childOrder == MainProcessEnum::CHILD_ORDER_1) {

                // 主单
                $pMainProcess = OpenShopMainProcessModel::where('pid', $this->orderModel->progressRel->pid)
                                                        ->where('childOrder', MainProcessEnum::CHILD_ORDER_0)
                                                        ->first();

                // 主单总金额 +
                $pSignOrder = OpenShopSignOrderModel::query()->where('mainProcessId', $pMainProcess->id)->first();
                $pSignOrder->payPrice += $this->orderModel->payPrice;
                $pSignOrder->shouldPayPrice += $this->orderModel->shouldPayPrice;
                $pSignOrder->save();

                // 子单总金额 -
                $this->orderModel->payPrice = 0;
                $this->orderModel->shouldPayPrice = 0;
                $this->orderModel->save();
            }
        }

        try {
            // 支付完成 - 触发下个阶段事件
            if ($this->signOrderModel->step == SignOrderEnum::STEP_4) {

                // 订单日志事件
                Cache::forget(OpenShopCacheEnum::getShopManagerPwd((string)optional($this->signOrderModel->baseInfoRel)->mobile));

                event(new OrderPaymentSucceededEvent($this->signOrderModel, $this->signOrderModel->payHistoryRel));
            }
        } catch (\Exception $e) {
            logException("支付回调 事件触发异常", $e, ["orderNo" => $this->signOrderModel->orderNo], true, true);

            // 支付成功 - 事件触发异常
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_SIGN_ORDER_PAY_SUCCESS_EVENT, $e->getMessage())
            );
        }
    }
}
